#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

const int BUFFER_SIZE = 1024;

int main(int argc, char* argv[]) 
{
    if (argc != 2) 
    {
        std::cerr << "Usage: server <port>\n";
        return 1;
    }

    int port = std::stoi(argv[1]);
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len = sizeof(client_addr);
    char buffer[BUFFER_SIZE];
    ssize_t bytes_received;

    // 创建服务器端套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket < 0) 
    {
        std::cerr << "Error creating socket\n";
        return 1;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(port);

    // 绑定套接字
    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) 
    {
        std::cerr << "Error binding socket\n";
        close(server_socket);
        return 1;
    }

    // 监听连接
    if (listen(server_socket, 5) < 0) 
    {
        std::cerr << "Error listening on socket\n";
        close(server_socket);
        return 1;
    }

    std::cout << "Server listening on port " << port << std::endl;

    // 接受客户端连接
    client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
    if (client_socket < 0) 
    {
        std::cerr << "Error accepting connection\n";
        close(server_socket);
        return 1;
    }

    // 接收消息
    bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
    if (bytes_received > 0) 
    {
        buffer[bytes_received] = '\0'; // Null-terminate the received data
        std::cout << "Received message: " << buffer << std::endl;

        // 获取客户端的IP地址和端口号
        char client_ip[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
        std::cout << "Client IP: " << client_ip << std::endl;
        std::cout << "Client Port: " << ntohs(client_addr.sin_port) << std::endl;
    } 
    else 
    {
        std::cerr << "Error receiving data from client\n";
    }

    // 关闭套接字
    close(client_socket);
    close(server_socket);

    return 0;
}

